package com.huafeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huafeng.commonutil.CheckUtils;
import com.huafeng.commonutil.IpUtils;
import com.huafeng.commonutil.JwtHelper;
import com.huafeng.mapper.SysUserMapper;
import com.huafeng.model.base.Result;
import com.huafeng.model.constant.IdConstant;
import com.huafeng.model.entity.SysLoginLog;
import com.huafeng.model.entity.SysRole;
import com.huafeng.model.entity.SysUser;
import com.huafeng.model.entity.SysUserRole;
import com.huafeng.model.enums.ResultCodeEnum;
import com.huafeng.model.exception.BusinessException;
import com.huafeng.model.vo.LoginVo;
import com.huafeng.model.vo.RouterVo;
import com.huafeng.model.vo.SysUserQueryVo;
import com.huafeng.service.SysMenuService;
import com.huafeng.service.SysRoleService;
import com.huafeng.service.SysUserRoleService;
import com.huafeng.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @author 花风
 * @date 2023/8/16 18:13
 * @Description SysUserServiceImpl
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private final ReentrantLock updateStatusLock = new ReentrantLock();

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public Result queryUserByPage(SysUserQueryVo sysUserQueryVo) {
        // 分页对象
        Page<SysUser> sysUserPage = new Page<>(sysUserQueryVo.getPage(), sysUserQueryVo.getLimit());

        // 获取查询参数
        String keyword = sysUserQueryVo.getKeyword();
        String createTimeBegin = sysUserQueryVo.getCreateTimeBegin();
        String createTimeEnd = sysUserQueryVo.getCreateTimeEnd();

        // 创建条件查询对象
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        // 参数校验
        if (StringUtils.isNotEmpty(keyword) && StringUtils.isNotBlank(keyword)){
            queryWrapper.like("name",keyword).or().like("username",keyword).or().like("phone",keyword);
        }

        Map<String,String> params = new HashMap<>();
        params.put("createTimeBegin",createTimeBegin);
        params.put("createTimeEnd",createTimeEnd);
        queryWrapper = CheckUtils.checkParams(queryWrapper,sysUserQueryVo,params);

        // 分页条件查询
        sysUserPage = this.page(sysUserPage,queryWrapper);
        return Result.ok(sysUserPage);
    }

    @Override
    public Result updateStatus(Long id, Integer status) {
        updateStatusLock.lock();
        try {
            boolean update = this.update().set("status", status).eq("id", id).update();
            return CheckUtils.check(update);
        }finally {
            updateStatusLock.unlock();
        }
    }

    @Override
    public Result login(LoginVo loginVo) {
        // 获取参数
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();

        // 根据用户名查找用户
        SysUser sysUser = this.query().eq("username", username).one();
        if (sysUser == null){
            throw new BusinessException(ResultCodeEnum.ACCOUNT_ERROR);
        }

        // 对输入的密码进行加密，然后匹配
        String encryptPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if (!Objects.equals(encryptPassword,sysUser.getPassword())){
            throw new BusinessException(ResultCodeEnum.PASSWORD_ERROR);
        }

        // 获取用户状态，判断是否已停用
        Integer status = sysUser.getStatus();
        if (status == null || status == 0){
            throw new BusinessException(ResultCodeEnum.ACCOUNT_STOP);
        }

        // 根据userId和username生成token
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());

        Map<String, String> map = Map.of("token", token);
        return Result.ok(map);
    }

    @Override
    public Result info(Long userId) {
        SysUser sysUser = this.query().eq("id", userId).one();
        if (sysUser == null){
            throw new BusinessException(ResultCodeEnum.DATA_ERROR);
        }

        Map<String,Object> userInfo = new HashMap<>();
        userInfo.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        userInfo.put("name",sysUser.getUsername());

        // 获取用户拥有的角色
        List<SysUserRole> sysUserRoles = sysUserRoleService.query().eq("user_id", userId).list();
        // 用户拥有的角色id
        List<Long> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        // 根据id查询角色
        List<SysRole> sysRoles = sysRoleService.query().in("id", roleIds).list();
        String roleNames = "[" + StringUtils.join(sysRoles.stream().map(SysRole::getRoleName).collect(Collectors.toList()), ",") + "]";
        userInfo.put("roles",roleNames);


        // 根据用户id获取菜单权限值
        List<RouterVo> routerVoList = sysMenuService.findUserMenulist(roleIds);
        userInfo.put("routers",routerVoList);
        // 根据用户id获取用户按钮权限
        List<String> permsList = sysMenuService.findUserPermsList(roleIds);
        userInfo.put("buttons",permsList);

        return Result.ok(userInfo);
    }

    @Override
    public Result saveUser(SysUser sysUser) {
        // 获取用户密码并进行加密操作
        String password = sysUser.getPassword();
        sysUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        // 保存信息
        boolean save1 = this.save(sysUser);

        // 创建用户角色对象
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getId());
        sysUserRole.setRoleId(IdConstant.DEFAULT_ROLE_ID);
        // 保存信息
        boolean save2 = sysUserRoleService.save(sysUserRole);

        return CheckUtils.check(save1 && save2);
    }
}
